import _ from 'lodash';
import React, { useCallback, useState, useRef } from 'react';
import { Alert, StyleSheet } from 'react-native';
import {
  SortableList,
  SortableListItemProps,
  View,
  TouchableOpacity,
  Text,
  Icon,
  Assets,
  Colors,
  Button,
} from 'react-native-ui-lib';
import { renderHeader } from '../ExampleScreenPresenter';
import { TestCase, TestSuite } from '@rnoh/testerino';

interface Item extends SortableListItemProps {
  text: string;
}

const data: Item[] = _.times(5, index => {
  let text = `${index}`;
  // if (index === 3) {
  //   text = 'Locked item';
  // }

  return {
    text,
    id: `${index}`,
  };
});

const SortableListScreen = () => {
  const [items, setItems] = useState<Item[]>(data);
  const [selectedItems, setSelectedItems] = useState<Item[]>([]);
  const [removedItems, setRemovedItems] = useState<Item[]>([]);
  const orderedItems = useRef<Item[]>(data);
  const [enableHaptic, setEnableHaptic] = useState(true);

  const toggleItemSelection = useCallback(
    (item: Item) => {
      if (selectedItems.includes(item)) {
        setSelectedItems(
          selectedItems.filter(
            selectedItem => ![item.id].includes(selectedItem.id),
          ),
        );
      } else {
        setSelectedItems(selectedItems.concat(item));
      }
    },
    [selectedItems, setSelectedItems],
  );

  const addItem = useCallback(() => {
    if (removedItems.length > 0) {
      orderedItems.current = orderedItems.current.concat(removedItems[0]);
      setItems(orderedItems.current);
      setRemovedItems(removedItems.slice(1));
    }
  }, [removedItems, setItems, setRemovedItems]);

  const removeSelectedItems = useCallback(() => {
    setRemovedItems(removedItems.concat(selectedItems));
    setSelectedItems([]);
    orderedItems.current = orderedItems.current.filter(
      item => !selectedItems.includes(item),
    );
    setItems(orderedItems.current);
  }, [
    setRemovedItems,
    removedItems,
    selectedItems,
    setItems,
    setSelectedItems,
  ]);

  const keyExtractor = useCallback((item: Item) => {
    return `${item.id}`;
  }, []);

  const onOrderChange = useCallback((newData: Item[]) => {
    console.log('New order:', newData);
    orderedItems.current = newData;
    Alert.alert('onOrderChange  newOrder:' + newData.map((value) => value.text));
  }, []);

  const renderItem = useCallback(
    ({ item, index: _index }: { item: Item; index: number }) => {
      const isSelected = selectedItems.includes(item);
      const { locked } = item;
      const Container = locked ? View : TouchableOpacity;
      return (
        <Container
          // TODO: fix Android selection color
          style={[
            styles.itemContainer,
            isSelected && styles.selectedItemContainer,
          ]}
          marginT={20}
          onPress={() => toggleItemSelection(item)}
          // overriding the BG color to anything other than white will cause Android's elevation to fail
          // backgroundColor={Colors.red30}
          centerV

          centerH={locked}
          paddingH-page>
          <View flex row spread centerV>
            {!locked && (
              <Icon
                source={Assets.icons.demo.drag}
                tintColor={Colors.$iconDisabled}
              />
            )}
            <Text center $textDefault={!locked} $textNeutralLight={locked}>
              {item.text}
            </Text>
            {!locked && (
              <Icon
                source={Assets.icons.demo.chevronRight}
                tintColor={Colors.$iconDefault}
              />
            )}
          </View>
        </Container>
      );
    },
    [selectedItems, toggleItemSelection],
  );


  return (
    <TestSuite name="SortableList">
      <TestCase itShould="例子: data, scale={2},onOrderChange,enableHaptic={true}">
        <View padding-20 style={[styles.height]}>
          <View flex bg-$backgroundDefault>
            <View flex useSafeArea>
              <SortableList
                enableHaptic={true} // 控制触觉反馈
                data={items}
                itemProps={{marginTop:20}}
                renderItem={renderItem}
                onOrderChange={onOrderChange}
                scale={2}
              />
            </View>
          </View>
        </View>
      </TestCase>

      <TestCase itShould="例子: scale={1.2},enableHaptic={false}">
        <View padding-20 style={[styles.height]}>
          <View flex bg-$backgroundDefault>
            <View flex useSafeArea>
              <SortableList
                enableHaptic={false} // 控制触觉反馈
                data={items}
                itemProps={{marginTop:20}}
                renderItem={renderItem}
                onOrderChange={onOrderChange}
                scale={1.2}
              />
            </View>
          </View>
        </View>
      </TestCase>
    </TestSuite>
  );
};

export default SortableListScreen;
const styles = StyleSheet.create({
  toggleContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  toggleText: {
    fontSize: 16,
    color: '#666',
  },
  toggleButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    marginHorizontal: 5,
    backgroundColor: '#eee',
    borderRadius: 4,
    fontSize: 14,
  },
  toggleButtonActive: {
    backgroundColor: Colors.primary,
    color: '#fff',
    fontWeight: 'bold',
  },
  status: {
    fontSize: 16,
    color: Colors.primary,
    marginTop: 5,
  },
  itemContainer: {
    height: 52,
    borderColor: Colors.$outlineDefault,
    borderBottomWidth: 1,
  },
  selectedItemContainer: {
    borderLeftColor: Colors.$outlinePrimary,
    borderLeftWidth: 5,
  },
  height: {
    height: 450,
  }
});
